package com.squid.base.utils;

import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Utils {
    /**
     * 常量字符串
     */
    private static final String CLASS_TYPE_STRING = "java.lang.String";

    /**
     * 合并List
     *
     * @param list1 list1
     * @param list2 list2
     * @return {@link List }<{@link T }>
     * @author jh
     * @date 2023/06/06
     */
    public static <T> List<T> mergeList(List<T> list1, List<T> list2) {
        return Stream.of(list1, list2).flatMap(Collection::stream).collect(Collectors.toList());
    }

    /**
     * Obj 转换为 map
     *
     * @param obj obj
     * @return {@link Map }<{@link String }, {@link Object }>
     * @author jh
     * @date 2023/05/17
     */
    public static Map<String, Object> objToMap(Object obj) throws Exception {
        Map<String, Object> map = new HashMap<>(16);
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            map.put(field.getName(), field.get(obj));
        }
        return map;
    }

    /**
     * 交集
     *
     * @param list1 list1
     * @param list2 list2
     * @return {@link List }<{@link T }>
     * @author jh
     * date 2023/06/15
     */
    public static <T> List<T> intersection(List<T> list1, List<T> list2) {
        list1.retainAll(list2);
        return list1;
    }

    /**
     * 比较字段
     *
     * @param bean1 bean1
     * @param bean2 bean2
     * @return {@link List }<{@link String }>
     */
    public static <T> List<String> compareField(T bean1, T bean2) {
        Class<?> class1 = bean1.getClass();
        Field[] declaredFields1 = class1.getDeclaredFields();
        List<String> list = new ArrayList<>();
        Arrays.stream(declaredFields1).forEach(
                x -> {
                    String name = x.getName();
                    x.setAccessible(true);
                    try {
                        if (x.getGenericType().getTypeName().equals(CLASS_TYPE_STRING)) {
                            String str1 = (String) x.get(bean1);
                            String str2 = (String) x.get(bean2);
                            if (StringUtils.hasText(str1) && StringUtils.hasText(str2)) {
                                if (!str1.equals(str2)) {
                                    x.set(name, str2);
                                    System.out.println("：由" + str1 + "改为" + str2);
                                }
                            }
                        }
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException(e);
                    }
                }
        );
        return list;
    }
}
